<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="网点名称" prop="oName">
        <el-input
          v-model="queryParams.oName"
          placeholder="请输入网点名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:outlet:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:outlet:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:outlet:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:outlet:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="outletList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="网点名称" align="center" prop="oName" />
      <el-table-column label="网点联系人" align="center" prop="oContact" />
      <el-table-column label="网点联系电话" align="center" prop="oPhone" />
      <el-table-column label="地图位置" align="center">
        <template slot-scope="scope">
          <span @click="showMap(scope.row.oLongitude , scope.row.oLatitude)">
            <el-button
              type="primary"
              plain
              size="mini"
            >查看地图</el-button>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:outlet:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:outlet:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改网点信息管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="网点名称" prop="oName" label-width="120px">
          <el-input v-model="form.oName" placeholder="请输入网点名称" label-width="120px" />
        </el-form-item>
        <el-form-item label="网点联系人" prop="oContact" label-width="120px">
          <el-input v-model="form.oContact" placeholder="请输入网点联系人" />
        </el-form-item>
        <el-form-item label="网点联系电话" prop="oPhone" label-width="120px">
          <el-input v-model="form.oPhone" placeholder="请输入网点联系电话" />
        </el-form-item>
        <el-form-item label="" label-width="120px">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            @click="openMapDialog">在地图中选择位置
          </el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看地图显示 -->
    <el-dialog
      title="地图显示"
      :visible.sync="mapDialogVisible"
      width="70%"
      append-to-body
    >
      <div id="map" style="height: 400px;"></div>
    </el-dialog>


    <!-- 添加或修改网点位置信息对话框 -->
    <el-dialog
      title="地图显示"
      :visible.sync="newMapDialogVisible"
      width="70%"
      append-to-body
    >
      <div id="map" style="height: 400px;"></div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmLocation">确定</el-button>
        <el-button @click="newMapDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listOutlet, getOutlet, delOutlet, addOutlet, updateOutlet } from "@/api/system/outlet";
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  name: "Outlet",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 网点信息管理表格数据
      outletList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      mapDialogVisible: false,
      newMapDialogVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        oName: null,
        oContact: null,
        oPhone: null,
        oLongitude: null,
        oLatitude: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        oName: [
          { required: true, message: "网点名称不能为空", trigger: "blur" }
        ],
        oContact: [
          { required: true, message: "网点联系人不能为空", trigger: "blur" }
        ],
        oPhone: [
          { required: true, message: "网点联系电话不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询网点信息管理列表 */
    getList() {
      this.loading = true;
      listOutlet(this.queryParams).then(response => {
        this.outletList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.mapDialogVisible = false
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        oId: null,
        oName: null,
        oContact: null,
        oPhone: null,
        oLongitude: null,
        oLatitude: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.oId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加网点信息管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const oId = row.oId || this.ids
      getOutlet(oId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改网点信息管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.oId != null) {
            updateOutlet(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOutlet(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const oIds = row.oId || this.ids;
      this.$modal.confirm('是否确认删除网点信息管理编号为"' + oIds + '"的数据项？').then(function() {
        return delOutlet(oIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/outlet/export', {
        ...this.queryParams
      }, `outlet_${new Date().getTime()}.xlsx`)
    },
    showMap(longitude, latitude) {
      this.mapLocation = {longitude, latitude};
      this.mapDialogVisible = true;
      AMapLoader.load({
        key: '77b44b6f84ac46b347e84a0ee471f45f',
        version: '1.4.15',
        plugins: ['AMap.Geocoder']
      }).then(AMap => {
        const center = longitude && latitude
          ? [longitude, latitude]
          : [111.56, 40.79];

        this.map = new AMap.Map('map', {
          center,
          zoom: 15
        });

        this.marker = new AMap.Marker({
          position: center,
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
          map: this.map
        });
      }).catch(e => {
        console.error("高德地图初始化失败：", e);
      });
    },

    confirmLocation() {
      this.form.rLongitude = this.mapLocation.longitude;
      this.form.rLatitude = this.mapLocation.latitude;
      this.newMapDialogVisible = false;
    },
    openMapDialog() {
      this.newMapDialogVisible = true;
      AMapLoader.load({
        key: '77b44b6f84ac46b347e84a0ee471f45f',
        version: '1.4.15',
        plugins: ['AMap.Geocoder']
      }).then(AMap => {
        const center = this.form.longitude && this.form.latitude
          ? [this.form.longitude, this.form.latitude]
          : [111.56, 40.79];

        this.map = new AMap.Map('map', {
          center,
          zoom: 15
        });

        if (this.form.longitude && this.form.latitude) {
          this.marker = new AMap.Marker({
            position: center,
            icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
            map: this.map
          });
        }

        this.map.on('click', (e) => {
          const {lng, lat} = e.lnglat;
          this.mapLocation = {longitude: lng, latitude: lat};

          if (this.marker) {
            this.marker.setPosition([lng, lat]);
          } else {
            this.marker = new AMap.Marker({
              position: [lng, lat],
              icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
              map: this.map
            });
          }
        });
      }).catch(e => {
        console.error("高德地图初始化失败：", e);
      });
    },
  }
};
</script>
